﻿using System;
using System.Net;
using System.Net.Mail;
using Castle.Core.Logging;
using VideoSeller.Core.Configuration;
using VideoSeller.Core.Interfaces;

namespace VideoSeller.Business.Providers
{
	public class SmtpClientProvider : IMailProvider
	{
		private readonly SmtpClient _smtpClient;
		private readonly IApplicationSettingsProvider _applicationSettingsProvider;
		private readonly string _from;

		public SmtpClientProvider(IApplicationSettingsProvider applicationSettingsProvider)
		{
			_applicationSettingsProvider = applicationSettingsProvider;
			var settings = _applicationSettingsProvider.SmtpMailSettings;

			_smtpClient = new SmtpClient
				{
					DeliveryMethod = settings.DeliveryMethod,
					Host = settings.Network.Host,
					Port = settings.Network.Port,
					Credentials = new NetworkCredential(settings.Network.UserName, settings.Network.Password)
				};
			_from = settings.From;
		}

		public bool Send(MailMessage message)
		{
			return Send(message, false);
		}

		public bool Send(MailMessage message, bool isHtml)
		{
			try
			{
				message.From = new MailAddress(_from);
				message.IsBodyHtml = isHtml;
				_smtpClient.Send(message);
			}
			catch (Exception e)
			{
				IoC.Resolve<ILogger>().Error(e.Message);
				return false;
			}

			return true;
		}
	}
}